"""
PlumeSoft 量化代码库
作者：PlumeSoft
用途：贝叶斯选币炼丹炉
"""

from datetime import datetime
from time import sleep
import requests
import json
import program.plumesoft_bys.bys_config as bys_cfg
from program.plumesoft_bys.bys_common import dbg, log


def get_upgrade_info_from_url(url: str):
    # 检查软件更新
    try:
        log(f"开始检查软件版本更新...")
        response = requests.get(url)
        if response.status_code == 200:
            data = response.text
            dbg(f"返回信息: {data}")
            js = json.loads(data)
            upgrade_info = eval(js["wiki"]["content"])
            dbg(f"升级信息: {upgrade_info}")
            return upgrade_info
        else:
            return None
    except:
        return None


def daily_check_app_upgrade(force=False):
    # 每天检查一次软件更新信息
    if not force:
        try:
            # 判断是否允许检查更新
            if not bys_cfg.daily_check_app_upgrade_info:
                return
            # 读取上次检查时间
            cfg = json.load(
                open(bys_cfg.app_upgrade_info_file, mode="r", encoding="utf8")
            )
            if cfg["last_check_time"] == str(datetime.now().date()):
                return
        except:
            pass

    try:
        # 从更新地址取得更新信息
        upgrade_info = get_upgrade_info_from_url(bys_cfg.app_upgrade)
        # 保存检查时间
        cfg = {"last_check_time": str(datetime.now().date())}
        json.dump(
            cfg,
            open(bys_cfg.app_upgrade_info_file, mode="w", encoding="utf8"),
            ensure_ascii=False,
            indent=2,
        )
        if (
            isinstance(upgrade_info, dict)
            and ("app_build" in upgrade_info.keys())
            and upgrade_info["app_build"] > bys_cfg.app_build
        ):
            delay_sec = 30
            log('=========================================================================================')
            log(f'发现新版本: {upgrade_info["app_version"]} build {upgrade_info["app_build"]}')
            log(f'新版本地址: {upgrade_info["app_url"]}')
            log(f"延时 {delay_sec} 秒后继续执行，如果不需要每天第一次启动时自动检查更新，可以到配置文件中关闭该功能。")
            log('=========================================================================================')
            sleep(delay_sec)

    except:
        pass

def print_copyright():
    print("\n")
    print("*****************************************************")
    print("* " + bys_cfg.app_name)
    print("* " + bys_cfg.app_version + f" build {bys_cfg.app_build}")
    print("* " + bys_cfg.app_url)
    print("*****************************************************\n")


if __name__ == "__main__":
    # 手工强制检查更新
    daily_check_app_upgrade(True)
